package com.lazyfish.superdir.controller;

import com.lazyfish.superdir.entity.Dir;
import com.lazyfish.superdir.entity.FatherDir;
import com.lazyfish.superdir.service.DirService;
import com.lazyfish.util.ResultBuild;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@CrossOrigin
@Controller
public class FileUpload {
    @Autowired
    private DirService dirService;
    @RequestMapping("/FileUpload")
    public @ResponseBody
    ResultBuild FileUpload(@RequestParam int id, @RequestParam String name, @RequestParam MultipartFile file, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (file.isEmpty()) {
            map.put("result", "error");
            map.put("msg", "上传文件不能为空");
        } else {
            String originalFilename = name;
            try {
                Dir dir = dirService.getDir(id);
                if(dir==null){
                    map.put("result", "id_no_found");
                }else if(dir.getCollect()==0){
                    map.put("result", "inactive");
                }
                else{
                    //创建要上传的路径
                    File fdir = new File(FatherDir.getPath()+"/"+dir.getName());
                    if (!fdir.exists()) {
                        fdir.mkdirs();
                    }
                    File local_file=new File(FatherDir.getPath()+"/"+dir.getName()+"/"+originalFilename);
                    if(local_file.exists()){
                        map.put("result", "file_exists");
                    }else{
                        //文件上传到路径下
                        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(fdir, originalFilename));
                        //coding
                        map.put("result", "success");
                    }
                }



            } catch (Exception e) {
                map.put("result", "error");
                map.put("msg", e.getMessage());

            }
        }

        return new ResultBuild(200,map);
    }
}
